package utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import entity.Users;
import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.GenerousBeanProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.Properties;


public class DruidUtils {

    private static DataSource ds;

    static {
        try {
            // 1.1 读取配置文件内容
            Properties props = new Properties();
            // 1.2 加载文件
            InputStream in = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            props.load(in);
            // 1.3 获取连接池 druid连接池
            ds = DruidDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 1 获取连接
    public static Connection getConnection() throws Exception {
        return ds.getConnection();
    }

    // 2 获取连接池 数据源, 将来给jdbc工具类使用, 如 DBUtils, mybatis
    public static DataSource getDataSource() throws Exception {
        return ds;
    }

    //	释放资源
    public static void close(Statement st, Connection conn) {
        close(null, st, conn);
    }


    public static void close(ResultSet rs, Statement st, Connection conn) {
        if (null != rs) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

        if (null != st) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != conn) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //这是一个使用该工具类的示例
    public static void main(String[] args) throws Exception {
        Connection conn = null;
        try {
            //从连接池获取连接
            conn = DruidUtils.getConnection();
            String sql = "select * from users ";
            QueryRunner queryRunner = new QueryRunner();
            BasicRowProcessor basicRowProcessor = new BasicRowProcessor(new GenerousBeanProcessor());
            List<Users> query = queryRunner.query(conn, sql, new BeanListHandler<>(Users.class, basicRowProcessor));
            for (Users users : query) {
                System.out.println(users);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //归还连接(没有Statement)
            close(null, conn);
        }
    }


}

